package com.xh.ssm.controller;

import com.xh.ssm.bean.Userinfo;
import com.xh.ssm.service.UserinfoService;
import com.xh.ssm.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author PangJunjie
 * @Date 2024/1/29/029
 */
@Controller
@RequestMapping("/userinfo")
public class UserinfoController {
    @Autowired
    private UserinfoService userinfoService;

    @GetMapping("/list")
    public String list() {
        return "userinfo/userinfo-list";
    }

    @GetMapping("/page")
    @ResponseBody
    public R page(int page, int limit, Userinfo userinfo, HttpSession session) {
        /*获取登录用户的信息，用来处理不同权限看到的表格数据不同
         * 管理员(roleId为1)可以看到所有的用户信息
         * 其他用户只能看到自己的信息
         * */

        Userinfo loginInfo = (Userinfo) session.getAttribute("loginInfo");
        if (loginInfo != null && loginInfo.getRoleId() != 1) {
            userinfo.setId(loginInfo.getId());
        } else {
            userinfo.setId(null);
        }
        return userinfoService.getPage(page, limit, userinfo);
    }

    @GetMapping("/edit")
    public String edit(Integer id, String type, Model model) {
        if (id != null) {
            model.addAttribute("userinfo", userinfoService.getById(id));
            model.addAttribute("type", type);
        }
        return "userinfo/userinfo-update";
    }

    @PostMapping(value = {"/update", "/password"})
    @ResponseBody
    public R update(Userinfo userinfo) {
        userinfoService.saveOrUpdate(userinfo);
        return R.ok();
    }

    @PostMapping("/status")
    @ResponseBody
    public R status(Userinfo userinfo, HttpSession session) {
        Userinfo loginInfo = (Userinfo) session.getAttribute("loginInfo");
        if (loginInfo.getId().equals(userinfo.getId())) {
            return R.error("当前用户无法更改状态！");
        }
        userinfoService.saveOrUpdate(userinfo);
        return R.ok();
    }

    @GetMapping("/password")
    public String password() {
        return "userinfo/userinfo-password";
    }

    @GetMapping("/check/password")
    @ResponseBody
    public R checkPassword(Userinfo userinfo) {
        return userinfoService.checkPassword(userinfo);
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public R delete(@PathVariable int id) {
        userinfoService.deleteById(id);
        return R.ok();
    }

    @GetMapping("/photo/{id}")
    @ResponseBody
    public R photo(@PathVariable int id) {
        return userinfoService.getImageList(id);
    }

    @GetMapping("/project/{id}")
    @ResponseBody
    public R project(@PathVariable int id) {
        return userinfoService.getProjectList(id);
    }
}
